import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { NoteType } from '@/types';
import type { Note, TodoItem, TodoStatus, TodoCategory } from '@/types';
import { generateId } from '@/utils/helpers';

export const useNoteStore = defineStore('note', () => {
  // 状态
  const notes = ref<Note[]>([]);
  const categories = ref<TodoCategory[]>([
    { id: 'family', name: '家庭待办', color: '#ff6b6b', description: '家庭相关事务' },
    { id: 'work', name: '公司待办', color: '#4ecdc4', description: '工作相关事务' },
    { id: 'part-time', name: '兼职待办', color: '#45b7d1', description: '兼职工作事务' },
    { id: 'personal', name: '个人待办', color: '#96ceb4', description: '个人事务' }
  ]);
  const currentNote = ref<Note | null>(null);
  const isLoading = ref(false);
  const error = ref<string | null>(null);

  // 计算属性
  const codeNotes = computed(() => 
    notes.value.filter(note => note.type === NoteType.CODE)
  );
  
  const diaryNotes = computed(() => 
    notes.value.filter(note => note.type === NoteType.DIARY)
  );
  
  const todoNotes = computed(() => 
    notes.value.filter(note => note.type === NoteType.TODO)
  );

  // 方法
  const addNote = (note: Omit<Note, 'id' | 'createdAt' | 'updatedAt'>) => {
    const newNote = {
      ...note,
      id: generateId(),
      createdAt: new Date(),
      updatedAt: new Date()
    } as Note;
    notes.value.push(newNote);
    saveToLocalStorage();
  };

  const updateNote = (id: string, updates: Partial<Note>) => {
    const index = notes.value.findIndex(note => note.id === id);
    if (index !== -1) {
      notes.value[index] = {
        ...notes.value[index],
        ...updates,
        updatedAt: new Date()
      };
      saveToLocalStorage();
    }
  };

  const deleteNote = (id: string) => {
    const index = notes.value.findIndex(note => note.id === id);
    if (index !== -1) {
      notes.value.splice(index, 1);
      saveToLocalStorage();
    }
  };

  const setCurrentNote = (note: Note | null) => {
    currentNote.value = note;
  };

  const addTodoItem = (noteId: string, todo: Omit<TodoItem, 'id' | 'createdAt' | 'updatedAt'>) => {
    const note = notes.value.find(n => n.id === noteId);
    if (note && note.type === NoteType.TODO) {
      const newTodo: TodoItem = {
        ...todo,
        id: generateId(),
        createdAt: new Date(),
        updatedAt: new Date()
      };
      note.todos.push(newTodo);
      note.updatedAt = new Date();
      saveToLocalStorage();
    }
  };

  const updateTodoItem = (noteId: string, todoId: string, updates: Partial<TodoItem>) => {
    const note = notes.value.find(n => n.id === noteId);
    if (note && note.type === NoteType.TODO) {
      const todo = note.todos.find(t => t.id === todoId);
      if (todo) {
        Object.assign(todo, updates, { updatedAt: new Date() });
        note.updatedAt = new Date();
        saveToLocalStorage();
      }
    }
  };

  const deleteTodoItem = (noteId: string, todoId: string) => {
    const note = notes.value.find(n => n.id === noteId);
    if (note && note.type === NoteType.TODO) {
      const index = note.todos.findIndex(t => t.id === todoId);
      if (index !== -1) {
        note.todos.splice(index, 1);
        note.updatedAt = new Date();
        saveToLocalStorage();
      }
    }
  };

  const addCategory = (category: Omit<TodoCategory, 'id'>) => {
    const newCategory: TodoCategory = {
      ...category,
      id: generateId()
    };
    categories.value.push(newCategory);
    saveToLocalStorage();
  };

  // 本地存储
  const saveToLocalStorage = () => {
    try {
      localStorage.setItem('daylog-notes', JSON.stringify(notes.value));
      localStorage.setItem('daylog-categories', JSON.stringify(categories.value));
    } catch (err) {
      console.error('保存到本地存储失败:', err);
    }
  };

  const loadFromLocalStorage = () => {
    try {
      const notesData = localStorage.getItem('daylog-notes');
      const categoriesData = localStorage.getItem('daylog-categories');
      
      if (notesData) {
        const parsedNotes = JSON.parse(notesData);
        // 转换日期字符串为 Date 对象
        notes.value = parsedNotes.map((note: any) => ({
          ...note,
          createdAt: new Date(note.createdAt),
          updatedAt: new Date(note.updatedAt),
          ...(note.type === NoteType.TODO && {
            todos: note.todos.map((todo: any) => ({
              ...todo,
              createdAt: new Date(todo.createdAt),
              updatedAt: new Date(todo.updatedAt),
              ...(todo.dueDate && { dueDate: new Date(todo.dueDate) })
            }))
          })
        }));
      }
      
      if (categoriesData) {
        categories.value = JSON.parse(categoriesData);
      }
    } catch (err) {
      console.error('从本地存储加载失败:', err);
    }
  };

  // 初始化
  loadFromLocalStorage();

  return {
    // 状态
    notes,
    categories,
    currentNote,
    isLoading,
    error,
    
    // 计算属性
    codeNotes,
    diaryNotes,
    todoNotes,
    
    // 方法
    addNote,
    updateNote,
    deleteNote,
    setCurrentNote,
    addTodoItem,
    updateTodoItem,
    deleteTodoItem,
    addCategory,
    saveToLocalStorage,
    loadFromLocalStorage
  };
}); 